from flask import request, Blueprint
from ding import data, tools, notice
import copy
import yaml
from dateutil import tz
from datetime import datetime
import json
import logging

ding = Blueprint('ding', __name__)


@ding.route('/')
def hello():
    return '<a href="https://gitee.com/yunwe/ding-talk"> ding-talk说明文档 </a>'


@ding.route('/webhook/send/<group>', methods=['POST'])
def webhook(group: str):
    """
    接收处理Alert Manager的JSON
    :param group: 指定告警推送的群组
    """
    try:
        alert_data = json.loads(request.data) if is_valid_json(request.data) else yaml.safe_load(request.data)
        logging.debug(alert_data)
    except ValueError:
        notice.Notice({"title": "alertmanager 数据格式无法解析!"}, group).push_center()
        return "alertmanager 数据格式无法解析!"
    for alerts in alert_data['alerts']:
        alert_msg = {
            'status': alerts['status'],
            **alerts['labels'],
            **alerts['annotations']
        }
        # 转换为时间戳
        date_obj = datetime.strptime(time_format(alerts['startsAt']), '%Y-%m-%d %H:%M:%S')
        alert_msg['TS'] = int(date_obj.timestamp() * 1000)

        if alerts['status'] == 'resolved':
            alert_msg['start_time'] = time_format(alerts['startsAt'])
            alert_msg['end_time'] = copy.deepcopy(time_format(alerts['endsAt']))
            data.msg_save(copy.deepcopy(alert_msg))
        elif alerts['status'] == 'firing':
            alert_msg['start_time'] = time_format(alerts['startsAt'])
        # 消息推送中心处理
        notice.Notice(alert_msg, group).push_center()

    return "default interface"


@ding.route('/encrypt/', methods=['POST'])
def encrypt():
    """
    账号密码加密
    """
    if not is_valid_json(request.data):
        return 'json格式不标准或者为空！'
    msg = json.loads(request.data)
    en_user = tools.salsa_encrypt(msg["username"])
    en_pw = tools.salsa_encrypt(msg["password"])
    return f"user: {bytes.decode(en_user)}  password: {bytes.decode(en_pw)}\n"


def time_format(utctime):
    """
    prometheus告警信息时间格式化
    :param utctime: 格林尼治时间
    """
    try:
        # 如果时间戳是纳秒级别的，去掉最后三位
        if len(utctime.split('.')[-1]) > 6:
            utctime = utctime[:-4] + 'Z'
        date_obj = datetime.strptime(utctime, '%Y-%m-%dT%H:%M:%S.%fZ')
        # 将日期对象转换为本地时区
        local_tz = tz.tzlocal()
        local_date_obj = date_obj.replace(tzinfo=tz.tzutc()).astimezone(local_tz)
        # 格式化日期对象
        formatted_date = local_date_obj.strftime('%Y-%m-%d %H:%M:%S')
    except ValueError:
        now = datetime.now()
        formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
        logging.info(f"无法解析的时间格式，替换为当前时间: {utctime}")
    return formatted_date


def is_valid_json(json_data):
    """
    判断合法json
    :param json_data json数据
    :return: True/False
    """
    try:
        json.loads(json_data)
    except ValueError:
        logging.error('无效的 JSON 数据')
        return False
    return True
